class StudList {
    constructor(divId, tableId,tableFilter) {

        let load = this;

        this.divId = divId;

        this.tableId = tableId;

        // this.bodyId = 

        this.tableFilter = tableFilter;

        this.tableSetup = {
            id: load.tableId,
            elem: "#"+load.tableId
            , defaultToolbar: ['filter', 'print', 'exports']
            // , height: 312
            , url: '/Lock/GetSomeAcc' //数据接口
            , where: { idCard: this.idCard, accrank: 3 }
            , page: true    //开启分页
            , toolbar: '#toolBar'
            , cols: [[ //表头
                { field: 'aid', title: '学号', width: '10%', edit: "text", sort: true, /*fixed: 'left'*/ }
                , { field: 'sname', title: '姓名', edit: "text", width: '10%' }
                , {
                    field: 'ssex', title: '性别',
                    templet: function (d) {
                        var tmpTrue = "", tmpFalse = "", str = "selected";
                        var htmlstr = "<form class='layui-form'><select name='SexSelect' value=" + d.tsex + " >";
                        console.log("--------------- sex --------------");
                        console.log(d.ssex);
                        if (d.ssex) tmpTrue = str;
                        else tmpFalse = str;
                        htmlstr += "<option value=" + true + " " + tmpTrue + ">男</option>";

                        htmlstr += "<option value=" + false + " " + tmpFalse + ">女</option>";

                        htmlstr += "</select></form>";

                        return htmlstr;

                    }
                    , width: '10%'
                }
                , {
                    field: 'sage', title: '年龄', edit: "text",
                    templet: function (d) {
                        if (d.tage == -1) return "";
                        else return d.sage;
                    }
                    , width: '10%', sort: true
                }
                , { field: 'sumCredit', title: '总学分', width: '10%' , sort: true}
                , {
                    field: 'edit', title: '编辑',
                    templet: "#tool-col-exit"
                    , width: '20%', sort: true, align: "center"
                }
            ]]
            , contentType: 'jsonp'//一定要是jsonp类型
            , parseData: function (res) { //res 即为原始返回的数据

                console.log(res);

                return {
                    "code": res.statue, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.count, //解析数据长度
                    "data": res.students //解析数据列表
                };
            }
            , request: {
                pageName: 'pageInd' //页码的参数名称，默认：page
                , limitName: 'rowCount' //每页数据量的参数名，默认：limit
            }
            , done: function (res, curr, count) {

                console.log("student_list");
                console.log(res);
                return;
            }
        }
    }

    start() {

        console.log(this.divId);

        $("#" + this.divId).show().siblings().hide();

        let load = this;

        load.render();
        

    }

    render(){

        let load = this;

        layui.table.render(load.tableSetup);

        load.addEvent();
    }


    addEvent(){

        let load = this;

        let table = layui.table;

        let form = layui.form;

        table.on('tool('+load.tableFilter+')', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"

            var layEvent = obj.event;
            var data = obj.data;

            var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）


            var btnLoad = this;


            if (layEvent === 'edit') { //编辑
                console.log("edit-------------------------");

                // 即在禁用状态点击其效果无效
                if ($(btnLoad).prop("class").indexOf(MyUtils.tableBtnDistabled) != -1) {
                    console.log("disabled");
                    return;
                }

                let editLoad = this;

                let flag = false;


                layer.confirm('确认修改？', { icon: 3, title: '提示' }, function (index) {
                    $(btnLoad).addClass("layui-btn-disabled");

                    layer.close(index);//关闭弹出层


                    //同步更新缓存对应的值
                    let select = $(editLoad).parents("tr").find("dd[class=layui-this]");//.attr("lay-value");
                    console.log("vak");

                    let ssex = select.eq(0).attr("lay-value");
                   
                    data["ssex"] = (ssex == "true" ? true : false);

                    console.log(data);
                    
                    // 对后端发出更新请求
                    $.ajaxSetup({ contentType: "application/json; charset=utf-8" });
                    $.get("/Lock/Update/Acc/Stud", { "student": JSON.stringify(data) }, function (resp) {
                        if (resp.statue == 0) {
                            // flag = true;
                            layer.msg(resp.message, { icon: 6 });
                        } else {
                            layer.msg(resp.message, { icon: 5 });
                        }
                        layui.table.render(load.tableSetup);
                    })
                    

                });


            } else if (layEvent === 'logout') {

                let flag = false;

                layer.confirm('确认注销用户吗？', function (index) {

                    layer.close(index);
                    //向服务端发送删除指令
                    $.get("/Lock/Delete/Acc/Stud", { 'aid': data['aid'] }, function (resp) {
                        if (resp.statue == 0) {
                            flag = true;
                            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                            load.render();
                            layer.msg(resp.message, { icon: 6 });

                        } else {
                            layer.msg(resp.message, { icon: 5 });
                        }
                    })

                });

            }else if(layEvent === 'resetpaw'){

                console.log("resetpaw");
                // return ;

                $.post('/Lock/Pwd/Reset',{'aid': data['aid'],'accrank':3},function(resp){
                    if (resp.statue == 0) {
                        layer.msg(resp.message, { icon: 6 });

                    } else {
                        layer.msg(resp.message, { icon: 5 });
                    }
                })
            }
        });


        table.on('edit('+load.tableFilter+')', function (obj) { //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
            
            console.log("edit");
            // console.log(this);
            MyUtils.startEditBtn(this);

        });


        form.on("select", function () {
            MyUtils.startEditBtn(this);
        });


        //触发事件
        table.on('toolbar('+load.tableFilter+')', function (obj) {

            console.log("toolbar");
            var id =(obj.config.id);                   
            switch (obj.event) {
                case 'add':
                    load.addLayerindex=layer.open({
                        type: 1,
                        shade: 0,
                        content: $('#id-body-stud-tab-table-add'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                      });
                    
                    
                    // layer.msg('添加');
                    break;
            };
        });


        load.addForm();
    }



    addForm(){


        let load = this;

        $("#id-body-stud-tab-table-add-form").on("submit",function(e){
            e.preventDefault();

            var formData = $(this).serializeArray();

            let studentJson = {};
         

            console.log(formData);

            for(let i =0 ;i<formData.length;i++){
                studentJson[formData[i]['name']] = formData[i]['value'];
            }


    
            $.ajax({
                type: "post",
                data: { 'student':JSON.stringify(studentJson)},
                url: "/Lock/Add/Acc/Stud",
                success: function(res){

                    console.log(res);
                    console.log("add-stud");
    
                    if(res.statue == 0){
                        // 添加成功后应该跳转
                        layer.msg(res.message, {icon: 6});  
                        layer.close(load.addLayerindex);
    
                    }else{
                        layer.msg(res.message,{icon: 5,time: 2000});
                    }

                    // load.render();
                    layui.table.render(load.tableSetup);
                    
                },
    
                error: function(){
                    console.log("超时");
                }
    
            });
    
            
    
    
        });//加载函数末
    
    }


}